<template>
	<div class="app-container">
		
		<div class="search-container  app_ny">
			<div class="div2" style="position: relative">
				<el-row :gutter="12" style="width: 100%">
					<el-col :span="4" >
						<el-tree-select
						style="width: 100%"
						v-model="queryParams.cid"
						:data="baseConfigStore.newExCompanyList"
						check-strictly
						clearable
						:render-after-expand="false" 
					
						placeholder="请选择所属公司" >
						<template v-slot:default="{node, data }">
								<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
							</template>
						</el-tree-select>	
					</el-col>
					<el-col :span="4">
						<el-tree-select
						v-model="queryParams.class_id"
						:data="classList"
						check-strictly
						:render-after-expand="false" 
						class="defalut-width"
						placeholder="请选择类目" 
						clearable
						:props="{
							label: 'class_name',
							children: 'children',
							value: 'id'}">
						</el-tree-select>	
					</el-col>
					<el-col :span="3">
						<el-input v-model="queryParams.name" placeholder="请输入标题" clearable />
					</el-col>
					<el-col :span="6" >
						<el-button :loading="loading"  type="primary" @click="handleQuery">
							<template #icon><i-ep-search /></template>查询</el-button>
					</el-col>
				</el-row>
				<FilterColumn
				 class="filtBox"
				 @handleRefresh="resetQuery()"
				:strtype="strtype"></FilterColumn>
			</div>	
		</div>

		<el-card shadow="never">
			
			<div class="action-row">
				<el-button v-hasPerm="['asset.Asset/save']"   @click="handleDo('','act_add')" type="primary" plain><template #icon><i-ep-plus /></template>新增</el-button>
				<el-button  @click="handleDo('', 'act_info')" :disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)" plain><template #icon><i-ep-document/></template>详情</el-button>
				<el-button v-hasPerm="['asset.Asset/update']" @click="handleDo('', 'act_edit')" :disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)" plain><template #icon><i-ep-edit/></template>修改</el-button>
				<el-button v-hasPerm="['asset.Asset/delete']"  @click="handleDo('', 'act_del')" :disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)" plain><template #icon><i-ep-delete/></template>删除</el-button>
				<el-button type="primary"  @click="onExport()"  plain><template #icon><i-ep-download/></template>导出</el-button>
			</div>
			
			<el-table :key="reload" ref="dataTableRef" 
			v-loading="loading"
			 :data="tableData" 
			 align="left"
				tooltip-effect="dark" 
				:show-overflow-tooltip="true" 
				:scrollbar-always-on="true" border
				@cell-mouse-enter="rowMouse"
				@cell-mouse-leave="menuLineVisible=false"
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column type="index" label="序号" align="center" width="80" />
				<template v-for="(item,index) in cColumnsList()" :key='index'>
					<el-table-column 
					:label="item.label" 
					:align="item.align"
					 :prop="item.prop" 
					 :width="item.width"
					 :min-width="item.minwidth"></el-table-column>
				</template>
			</el-table>
			<pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
				v-model:limit="queryParams.limit" @pagination="handleQuery" />
		</el-card>

		<!-- 新增资产 or 编辑资产 or 查看资产 -->
		
		<assetEdit 
			v-if="dialogAdd.visible" 
			v-model="dialogAdd.visible" 
			:dialogTitle="dialogAdd.title"
			:dialogTableValue="dialogAdd.value" 
			:dialogStatus="dialogAdd.status" 
			@initRefreshList="handleQuery">
		</assetEdit>
		
		<!-- 放款记录 -->
		
		
		
	</div>
</template>
<script setup lang="ts">
	defineOptions({
		name: "Doc",
		inheritAttrs: false,
	});
	import { parseQuery, useRoute } from 'vue-router';
	import router from '@/router';
	import { useUserStore } from "@/store/modules/user";
	import { useTableFilterStore } from "@/store/modules/tableFilter";
	import { useBaseConfigStore } from "@/store/modules/baseConfig";
	const baseConfigStore = useBaseConfigStore();
	//接口地址
	import {
		getAssetList,
		getAssetDel,
		getAssetClass,
		exportAssetList
	} from "@/api/asset";
	const TableFilter = useTableFilterStore();
	const userStore = useUserStore();
	const strtype = ref('asset');

	// 表格标题
	const cTitles = [ "标题", "所属公司","权属单位", "所属类目", "操作人"];
	// 显示字段
	const sTitles = ["标题", "所属公司","权属单位", "所属类目", "操作人"];
	// 字段属性
	const cColumns = [
	
		{ label: "标题", prop: "name", align: "center", minwidth: 200 },
		{ label: "所属公司", prop: "company.name", align: "center", minwidth: 200 },
		{ label: "权属单位", prop: "unit_info.name", align: "center", minwidth: 200 },
		{ label: "所属类目", prop: "class_info.class_name", align: "center", minwidth: 200 },
		{ label: "操作人", prop: "user.name", align: "center", minwidth: 150 }
	]

	interface TableGlobalLocal {
		[key : string] : any; // 或者更具体的类型
	}
	// 列表渲染
	function cColumnsList() {
		const ColumnsList = (TableFilter.tableGlobalLocal as TableGlobalLocal)[strtype.value + '_checklist'];
		if (ColumnsList) {
			const columnMap : any = {}; // 创建一个对象来存储cColumns中label和对象的映射  
			// 预先建立label到对象的映射  
			for (const column of cColumns) {
				columnMap[column.label] = column;
			}
			const newList = [];
			for (const label of ColumnsList) {
				// 尝试从映射中获取对象  
				const foundColumn = columnMap[label];
				if (foundColumn) {
					// 如果找到了，则添加到newList中  
					newList.push(foundColumn);
				}
			}
			return newList;
		}
		else {
			return [];
		}
	};
	// 列表-数据列初始化
	function columnsInit() {
		const dropColStr : string = strtype.value + '_dropCol';
		const checklistStr : string = strtype.value + '_checklist';
		const drop_col : any = (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[dropColStr];
		const checklist = (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[checklistStr];
		if (!drop_col) {
			(TableFilter.tableGlobalLocal as TableGlobalLocal)[dropColStr] = JSON.parse(JSON.stringify(cTitles));
			(TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[dropColStr] = JSON.parse(JSON.stringify(cTitles));
		}
		if (!checklist) {
			(TableFilter.tableGlobalLocal as TableGlobalLocal)[checklistStr] = JSON.parse(JSON.stringify(sTitles));
			(TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[checklistStr] = JSON.parse(JSON.stringify(sTitles));
		}
	}



	const queryParamsData={
		page: 1,
		limit: 20,
		name: "",//标题搜索
		cid: "",
		class_id: ""
	}
	//搜索-字段配置
	const queryParams = reactive(JSON.parse(JSON.stringify(queryParamsData)));
	
	const loading = ref(false);
	const total = ref(0);
	const route = useRoute();
	const tableData = ref([]);// table表格数据
	const reload = ref();
	const multipleSelection =ref<any>([]);
	const menuLineVisible =ref(true);
	const rowR = ref<any>({});
	
	const dialogAdd = reactive<any>({
		title: "添加信息", //弹窗标题
		visible: false,   //弹窗显示or隐藏
		status: "add_art", //弹窗状态类型  :添加 add_art 编辑 edit_art 详情 detail_art  
		value: {}   		  //携带整条参数 row
	});
	
	// 行菜单事件
	function rowMouse(row:any) {
		menuLineVisible.value = true
		rowR.value = row
	}
	// 数据多选事件
	function handleSelectionChange(val:any) {
		multipleSelection.value = val
	}
	// 操作按钮样式
	function buttonType(val:number) {
		if (val === 1) {
			return 'primary'
		} else {
			return 'info'
		}
	}
	
	// 操作
	 function handleDo(row:any, act:string) {
		dialogAdd.status = act
		switch (act) {
			case 'act_add':
				dialogAdd.visible = true;
				dialogAdd.title = '添加信息';
				dialogAdd.value = {};
				break
			case 'act_info':
				var rowItem= JSON.parse(JSON.stringify(row || multipleSelection.value[0]))
				dialogAdd.visible = true;
				dialogAdd.title = '查看详情';
				dialogAdd.value = rowItem;
				break
			case 'act_edit':
				var rowItem= JSON.parse(JSON.stringify(row || multipleSelection.value[0]))
				dialogAdd.visible = true;
				dialogAdd.title = '修改信息';
				dialogAdd.value = rowItem;
				break
			case 'act_del':
				handleDelete(JSON.parse(JSON.stringify(row || multipleSelection.value[0])))
				break
			default:	
		}
	}


	//获取资产列表
	function handleQuery() {
		loading.value = true;
		getAssetList(queryParams).then((res) => {
			console.log(res);
			tableData.value = res.data.list;
			total.value = res.data.count;
		}).finally(() => {
			loading.value = false;
		})
	}

	function handleDelete(row:any) {
		const Ids =row.id;
		if (!Ids) {
			ElMessage.warning("请勾选删除项");
			return;
		}
		ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		}).then(() => {
			loading.value = true;
			getAssetDel({
				id: Ids
			}).then((res) => {
				console.log(res)
				ElMessage({
					message: '删除成功',
					type: 'success'
				})
				handleQuery();
			}).finally(() => {
				loading.value = false;
			})
		}, function () {
			console.log('取消删除')
		});
	}
	/**
	 * 重置查询
	 */
	function resetQuery() {
		handleQuery();
	}
	
	
	function onExport() {
		exportAssetList(queryParams).then((response : any) => {
			const blob = new Blob([response.data], {
				type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
			});
			const a = document.createElement("a");
			const href = window.URL.createObjectURL(blob); // 下载的链接
			a.href = href;
			a.download = decodeURI(
				response.headers["content-disposition"].split(";")[1].split("=")[1]
			); // 获取后台设置的文件名称
			document.body.appendChild(a);
			a.click(); // 点击导出
			document.body.removeChild(a); // 下载完成移除元素
			window.URL.revokeObjectURL(href); // 释放掉blob对象
		});
	}

	
	const classList = ref<any>([]);
	onMounted(() => {
		handleQuery();
		columnsInit();
		getAssetClass(queryParams).then((res) => {
		    classList.value = res.data;
		}).finally(() => {
		  
		})
	})
</script>
<style lang="scss" scoped>
	::v-deep .cuslabel {
		width: 100px !important;
	}

	::v-deep .el-timeline-item__timestamp {
		font-size: 18px;
		color: #409eff;
		font-weight: bold;
		margin-bottom: 16px;
		padding-top: 1px;
	}

	::v-deep .tabs-prog .el-tabs__header {
		margin-bottom: 30px;
	}
</style>